package com.bjsxt.set1;

import java.util.Set;
import java.util.TreeSet;

/**
 * 问题1：为什么HashSet、LinkedHashSet存储String是唯一的，但是存储Student不唯一了
 *
 * 问题2：为什么TreeSet存储String是有序的，但是存储Student却报异常：
 * java.lang.ClassCastException: Student cannot be cast to Comparable
 *
 * 原因：String是系统类，应该已经做了某些操作，Student是自定义类，某些操作还没有做
 *
 * 问题1解决：重写equals()和hashCode()，缺一不可
 *
 * 问题2：
 *
 */
public class TestSet3 {
    public static void main(String[] args) {
        //创建set集合对象
        //Set<Student> set = new HashSet();
        //Set<Student> set = new LinkedHashSet();
        //Comparator comp = new StuScoreNameDescComparator();
        /*
        Comparator comp =new Comparator<Student>(){
            @Override
            public int compare(Student stu1, Student stu2) {
                if(stu1.getScore()>stu2.getScore()){
                    return 1;
                }else if(stu1.getScore()<stu2.getScore()){
                    return -1;
                }else{
                    // return 0;
                    return -stu1.getName().compareTo(stu2.getName());
                }
            }
        };

        Set<Student> set = new TreeSet(comp);//外部比较器优先



        Set<Student> set = new TreeSet<Student>((stu1,stu2)->{if(stu1.getScore()>stu2.getScore()){
            return 1;
        }else if(stu1.getScore()<stu2.getScore()){
            return -1;
        }else{
            // return 0;
            return -stu1.getName().compareTo(stu2.getName());
        }});

         */
        //Set<Student> set = new TreeSet<Student>((stu1,stu2)->{return -stu1.getName().compareTo(stu2.getName());});
        Set<Student> set = new TreeSet<Student>((stu1,stu2)->-stu1.getName().compareTo(stu2.getName()));
        //使用set存储多个学生信息
        Student stu1 = new Student("zhangsan","男",23,98);
        Student stu2 = new Student("lisi","男",24,87);
        Student stu3 = new Student("wangwu","男",23,98);
        Student stu4 = new Student("zhangsan","男",23,98);


        set.add(stu1);
        set.add(stu2);
        set.add(stu3);
        set.add(stu4);
        //遍历集合
        System.out.println(set.size());//??
        for(Student stu:set){
            System.out.println(stu);
        }

    }
}
